package com.teamwork.module03.service.publish.impl;

import com.teamwork.common.entity.module03.Article;
import com.teamwork.common.result.Result;
import com.teamwork.module03.service.ArticleService;
import com.teamwork.module03.service.AuthorService;
import com.teamwork.module03.service.MessageService;
import com.teamwork.module03.service.file.UploadService;
import com.teamwork.module03.service.publish.PublishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 文章发布实现类
 */
@Service
@Slf4j
public class PublishServiceImpl implements PublishService {

    @Resource
    private ArticleService articleService;
    @Resource
    private AuthorService authorService;
    @Resource
    private UploadService uploadService;



    /**
     * 发布文章
     * @param title 文章标题
     * @param content 文章内容
     * @param cover 文章封面
     * @return result
     */
    @Override
    public Result publish(Integer userid, String title, String content, MultipartFile cover) throws IOException {

        if( (title==null||title.equals("")) || (content==null||content.equals("")) ||
         cover==null){
            return Result.failure("内容不能为空！");
        }

        Long authorid = authorService.getByUserId(userid).getId();

        //设置基本信息
        Article article = new Article();
        article.setAuthorId(authorid);
        article.setTitle(title);
        article.setLikes(0);
        article.setComments(0);
        article.setShares(0);
        article.setStatus(0);

        boolean b = articleService.save(article);
        if(!b){
            log.info("用户id:{}发布文章存入数据库失败!!!",userid);
            return Result.failure("发布失败！后台错误1！");
        }
        Long articleId = article.getId();
        //上传文章内容
        String contentPath = uploadService.uploadContent(articleId, userid, content);
        //上传文章封面
        String coverPath = uploadService.uploadCover(articleId, userid, cover);
        //保存到数据库中字段
        article.setCover(coverPath);
        article.setContent(contentPath);
        //修改
        boolean b2 = articleService.updateById(article);
        if(!b2){
            log.error("用户id:{}发布文章存入数据库封面和内容字段失败！！！",userid);
            return Result.failure("发布失败！后台错误2！");
        }



        return Result.success("发布成功！等待审核");
    }
}
